package com.hins.search;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: 二分查找
 *
 * @author wenjiaqi
 * @date 2021/5/10 14:47
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = { 1, 8, 10, 89,1000,1000, 1234 };
        System.out.println(binarySearch2(arr, 0, arr.length - 1, 1000));
    }

    public static int binarySearch(int[] arr, int left, int right, int finalVal) {
        if (left > right) {
            return -1;
        }

        int mid = (left + right) / 2;
        int midVal = arr[mid];

        if (finalVal > midVal) {
            return binarySearch(arr, mid + 1, right, finalVal);
        } else if (finalVal < midVal) {
            return binarySearch(arr, left, mid - 1, finalVal);
        } else {
            return mid;
        }
    }

    public static List<Integer> binarySearch2(int[] arr, int left, int right, int finalVal) {
        if (left > right) {
            return new ArrayList<>();
        }

        int mid = (left + right) / 2;
        int midVal = arr[mid];

        if (finalVal > midVal) {
            return binarySearch2(arr, mid + 1, right, finalVal);
        } else if (finalVal < midVal) {
            return binarySearch2(arr, left, mid - 1, finalVal);
        } else {
            List<Integer> resIndexlist = new ArrayList<Integer>();

            int temp = mid - 1;

            while (temp >= 0 && arr[temp] == arr[mid]) {
                resIndexlist.add(temp);
                temp--;
            }

            resIndexlist.add(mid);

            while (temp <= arr.length - 1 && arr[temp] == arr[mid]) {
                resIndexlist.add(temp);
                temp++;
            }

            return resIndexlist;
        }

    }
}
